package org.easySpace.common.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author lzh@aginome.com
 * @description 该注解用于记录方法执行时间
 * @date 2023/03/20
 **/

@Aspect
@Slf4j
@Component
public class MethodTimePrintAspect {

    @Pointcut("@annotation(MethodTimePrint)")
    public void pointcutName() {
    }

    @Around("pointcutName()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 获取方法名(类全路径+.+方法名)
        String classFullName = pjp.getSignature().getDeclaringTypeName();
        String className = classFullName.substring(classFullName.lastIndexOf(".") + 1);
        // 比如：com.xxx.XxxService.xxxMethod
        String name = className + "." + pjp.getSignature().getName();
        // 记录开始时间
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        // 记录结束时间和用时
        log.info("方法:" + name + ", 耗时" + (System.currentTimeMillis() - start) + "ms");
        return result;
    }
}
